package cn.akaba.yun.controller;

import cn.akaba.yun.appCls.AppRequest;
import cn.akaba.yun.appCls.AppStringTool;
import cn.akaba.yun.appCls.AppVar;
import org.apache.tomcat.util.json.JSONParser;
import org.apache.tomcat.util.json.ParseException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;

@RestController
public class BaiduController {

    @GetMapping("/baidu")
    public RedirectView baidu() {
//        return "baidu";
        RedirectView view = new RedirectView();
        String url = AppVar.getUrlTplAuth();
        view.setUrl(url);
        System.out.println("go to baidu:");
        System.out.println(url);
        return view;
    }

    @GetMapping("/baidu/auth")
    public String baiduAuth(
        @RequestParam(value = "code", defaultValue = "") String code
    ) {
        String jsonStr = this.ajaxGetAuthTokenInfo(code);
        JSONParser jsonParser = new JSONParser(jsonStr);
        try {
            LinkedHashMap<String, Object> result = jsonParser.parseObject();
            String refreshToken = (String) result.get("refresh_token");
            String accessToken = String.valueOf(result.get("access_token"));
            String scope = String.valueOf(result.get("scope"));
            long expiresIn = ((BigInteger) result.get("expires_in")).longValue();
            System.out.println(expiresIn);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return jsonStr;
    }

    protected String ajaxGetAuthTokenInfo(String code) {
        return "{\"expires_in\":2592000,\"refresh_token\":\"122.61101cb0dbc26e3c80bc7e870cc0f081.YG5-cQe3jA96JgLDDI5cuHnG-WTeh3a-F18mIPw.rDD4dg\",\"access_token\":\"121.9271aa25fad38c141057f795b639fdd4.YnlEM38aoRREjIqOKLrbTG4R0Lzi8Brb8bcsQV5.tJpxVA\",\"session_secret\":\"\",\"session_key\":\"\",\"scope\":\"basic netdisk\"}";
//        String url = AppVar.getUrlAccessToken(code);
//        return AppRequest.getRequestString(url);
    }
}
